package tjs.study.mini.springbootstartsmini.autoconfigure.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.MultiValueMap;

import java.util.List;
import java.util.Map;

public class OnClassCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        MultiValueMap<String, Object> classesMap = metadata.getAllAnnotationAttributes(ConditionalOnClass.class.getName(), true);
        if (classesMap.isEmpty()) {
            return true;
        }
        for (Map.Entry<String, List<Object>> entry : classesMap.entrySet()) {
            List<Object> classNames = entry.getValue();
            for (Object className : classNames) {
                String[] classNameArr = (String[]) className;
                for (String classNameDetail : classNameArr) {
                    if (!ClassUtils.isPresent(String.valueOf(classNameDetail), context.getClassLoader())) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}